#include <iostream>
#include <unistd.h>
#include <cassert>
#include <stdio.h>
#include <cerrno>
#include <cstring>
#include <sys/wait.h>

using namespace std;
int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(!n);
    (void)n; // 只是为了防止编译器报警

    int rid = fork();
    if (rid < 0)
    {
        perror("fork");
        return -1;
    }
    if (rid == 0)
    {
        // 子进程负责写入
        close(pipefd[0]);
        // 写入数据
        int cnt = 1;
        while (true)
        {
            // char buffer[1024];
            // snprintf(buffer, sizeof(buffer), "hello father,pid:%d , cnt: %d", getpid(), cnt);
            // write(pipefd[1], buffer, strlen(buffer));
            // cnt--;
            // sleep(5);

            write(pipefd[1], "a", 1);
            cout << "write..." << cnt << endl;
            ++cnt;
            sleep(1);
        }
        close(pipefd[1]);
        exit(0);
    }

    // 父进程负责读取
    close(pipefd[1]);
    // 负责读取
    char buffer[1024];
    int cnt=1;
    while (true)
    {
        ssize_t ret = read(pipefd[0], buffer, sizeof(buffer) - 1);
        if (ret > 0)
        {
            buffer[ret] = 0;
            cout << getpid() << ":read child message,child say#" << buffer << endl;
        }
        if (ret == 0)
        {
            cout << "child exit!!! me too!! " << endl;
            break;
        }
        if (cnt == 5)
            break;
        cnt++;
        sleep(1);
    }

    close(pipefd[0]);
    int status = 0;
    int id = waitpid(-1, &status, 0);
    if (id == rid)
    {
        cout << "father wait success!!! sig:" << (status & 0xFF) << endl;
    }
    return 0;
}